package com.gin.kotlin.no_gay_alliance.activity.replyhistory

import android.content.Context
import android.content.Intent
import com.gin.kotlin.no_gay_alliance.adapter.replyhistory.ReplyHistoryTaskLogAdapter
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingActivity
import com.gin.kotlin.no_gay_alliance.database.dao.ReplyHistoryTaskLogDao
import com.gin.kotlin.no_gay_alliance.databinding.ActivityReplyHistoryTaskLogBinding
import com.gin.kotlin.no_gay_alliance.worker.ReplyHistoryTaskScannerWorker.Companion.DELAY_SECONDS
import java.time.ZonedDateTime

class ReplyHistoryTaskLogActivity : AbstractBindingActivity<ActivityReplyHistoryTaskLogBinding>() {
    private lateinit var autoRefresh: Runnable
    private lateinit var adapter: ReplyHistoryTaskLogAdapter
    private lateinit var dao: ReplyHistoryTaskLogDao
    private var taskId: Int = 0
    private var after: ZonedDateTime? = null
    override fun onCreate() {
        this.dao = App.INSTANCE.database.replyHistoryTaskLogDao()
        this.adapter = ReplyHistoryTaskLogAdapter(this, handler!!)
        this.autoRefresh = Runnable { query() }
        b?.recyclerView?.adapter = adapter
        b?.swipeRefreshLayout?.setOnRefreshListener { query() }
        query()
    }

    override fun onResume() {
        super.onResume()
        setToolbarTitle("任务日志")
    }

    private fun query() {
        // 取消原本的延迟自动刷新
        handler?.removeCallbacks(autoRefresh)
        b?.swipeRefreshLayout?.isRefreshing = true
        val list = dao.listByTaskId(taskId, after)
        adapter.pushData(list, 0)
        after = ZonedDateTime.now()
        ui {
            b?.recyclerView?.scrollToPosition(0)
            b?.swipeRefreshLayout?.isRefreshing = false
        }
        // 设置延迟自动刷新
        uiDelayed(DELAY_SECONDS * 1000, autoRefresh)
    }

    override fun handleIntent(intent: Intent) {
        this.taskId = intent.getIntExtra(KEY_ARGUMENT, 0).takeIf { it > 0 } ?: throw RuntimeException("非法的参数")
    }

    companion object {
        private const val KEY_ARGUMENT = "task_id"


        @JvmStatic
        fun start(context: Context, taskId: Int) {
            val starter = Intent(context, ReplyHistoryTaskLogActivity::class.java).putExtra(KEY_ARGUMENT, taskId)
            context.startActivity(starter)
        }
    }
}